<!-- 新增客户端组 -->
<template>
  <div>
    <a-drawer :title="$t('Add-new') + $t('Client-group')" :visible="drawerVisible" width="40%" :body-style="drawerBodyStyle"
      @close="handleCancel" :maskClosable="false">
      <a-form :form="form" :layout="formDirection">
        <!-- 组名 -->
        <a-form-item :label="$t('User-group-name')" v-bind='formLayout'>
          <a-input v-decorator="['groupName', {
            rules: [
              { required: true, message: $t('Enter') + $t('User-group-name') },
              { pattern: /^[a-zA-Z][a-zA-Z0-9_-]{2,31}$/, message: $t('Not_enter_special_characters6') }
            ],
          }]" :placeholder="$t('Enter') + $t('User-group-name')">
          </a-input>
        </a-form-item>
        <!-- 访问路径 -->
        <a-form-item :label="$t('Access-path')" v-bind="formLayout">
          <a-spin :spinning="isLoadingForm">
            <a-select v-decorator="['target', {
              rules: [{ required: true, message: $t('Choose') + 'target' }]
            }]" :placeholder="$t('Choose') + 'target'">
              <!-- @change="changeTarget" -->
              <a-select-option v-for="i in targetsData" :value='i' :key="i">{{ i }}</a-select-option>
            </a-select>
          </a-spin>
        </a-form-item>
        <!-- 配置客户端 -->
        <a-form-item :label="$t('Configure-client')" v-bind='formLayout'>
          <a-form-item v-for="(k, index) in form.getFieldValue('keys')" :key="k" label="" :required="false">
            <!-- v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
            :label="index === 0 ? $t('Client') : ''" -->
            <a-input v-decorator="[
              `clients[${k}]`,
              {
                validateTrigger: ['change', 'blur'],
                rules: [
                  { required: true, whitespace: true, message: $t('Enter') + $t('Client'), },
                  { pattern: clientNameReg, message: $t('Iqn-reg') },
                  { validator: validatorClientName },
                ],
              },
            ]" :placeholder="$t('Enter') + $t('Client')" style="width: 94%; margin-right: 8px" />
            <a-icon class="dynamic-delete-button" type="minus-circle-o" @click="() => remove(k)" />
            <!-- 
              :disabled="form.getFieldValue('keys').length === 1"
              v-if="form.getFieldValue('keys').length > 1" -->
          </a-form-item>
          <a-form-item v-bind="formItemLayoutWithOutLabel">
            <a-button type="dashed" style="width: 85%" @click="add">
              <a-icon type="plus" /> {{ $t('Add-client') }}
            </a-button>
          </a-form-item>
          <!-- <a-transfer
		  			:data-source="clientData"
		  			:titles="[$t('Optional-client'), $t('Selected-client')]"
		  			show-search
		  			:filter-option="filterOption"
		  			:target-keys="targetClientKeys"
		  			:render="renderRowData"
		  			@change="changeClientTransfer"
		  			:listStyle="{width:'45%',height:'350px'}"
		  			:locale="clientTransferLocale"
            id="clientTransferId"
            v-decorator="['client',{
              rules:[
                {required:true, message: $t('Enter')+$t('User-group-name')},注释
              ]
            }]"
		  		/> -->
        </a-form-item>
        <div v-if="form.getFieldValue('keys') && form.getFieldValue('keys').length !== 0" class="form-title"
          :style="chapChecked ? {} : { 'margin-bottom': '30px' }">
          <a-checkbox :checked="chapChecked" @change="changeChapCheck">
            <span v-if="$store.state.language == 'zh'">启用chap认证</span>
            <span v-else>Enable Chap Authentication</span>
          </a-checkbox>
        </div>
        <!-- chap认证 -->
        <a-row :gutter="15" v-if="chapChecked">
          <!-- 用户名 -->
          <a-col :span="12">
            <a-form-item :label="$t('User') + $t('Name')" v-bind='formLayout'>
              <a-input v-decorator="['username', {
                rules: [
                  { required: true, message: $t('Enter') + $t('User') + $t('Name') },
                  { pattern: /^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/, message: $t('Not_enter_special_characters2') }]
              }]" :placeholder="$t('Enter') + $t('User') + $t('Name')">
              </a-input>
            </a-form-item>
          </a-col>
          <!-- 密码 -->
          <a-col :span="12">
            <a-form-item :label="$t('Password')" v-bind='formLayout'>
              <a-input-password v-decorator="['pwd', {
                rules: [
                  { required: true, message: $t('Enter') + $t('Password') },
                  { pattern: /^[0-9a-zA-Z@_/-]{12,16}$/, message: $t('Not_enter_special_characters3') }
                ]
              }]" :placeholder="$t('Enter') + $t('Password')">
              </a-input-password>
            </a-form-item>
          </a-col>
        </a-row>
        <div class="form-title" v-if="chapChecked" :style="twoWayChecked ? {} : { 'margin-bottom': '30px' }">
          <a-checkbox :checked="twoWayChecked" @change="changeTwoWayCheck">
            <span v-if="$store.state.language == 'zh'">启用双向认证</span>
            <span v-else>Enable Two-Way Authentication</span>
          </a-checkbox>
        </div>
        <!-- 双向认证 -->
        <a-row :gutter="15" v-if="twoWayChecked">
          <!-- 反向用户名 -->
          <a-col :span="12">
            <a-form-item :label="$t('Reverse-user-name')" v-bind='formLayout'>
              <a-input v-decorator="['reverse_username', {
                rules: [
                  { required: true, message: $t('Enter') + $t('Reverse-user-name') },
                  { pattern: /^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/, message: $t('Not_enter_special_characters2') }]
              }]" :placeholder="$t('Enter') + $t('Reverse-user-name')">
              </a-input>
            </a-form-item>
          </a-col>
          <!-- 反向用户密码 -->
          <a-col :span="12">
            <a-form-item :label="$t('Reverse-user-password')" v-bind='formLayout'>
              <a-input-password v-decorator="['reverse_pwd', {
                rules: [
                  { required: true, message: $t('Enter') + $t('Reverse-user-password') },
                  { pattern: /^[0-9a-zA-Z@_/-]{12,16}$/, message: $t('Not_enter_special_characters3') }
                ]
              }]" :placeholder="$t('Enter') + $t('Reverse-user-password')">
              </a-input-password>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 配置lun -->
        <a-form-item :label="$t('Config-lun')" v-bind='formLayout'>
          <a-spin :spinning="isLoadingForm">
            <a-transfer :data-source="lunData" :titles="[$t('Optional-lun'), $t('Selected-lun')]" show-search
              :filter-option="filterOption" :target-keys="targetLunKeys" :render="renderRowData"
              @change="changeLunTransfer" :listStyle="{ width: '45%', height: '350px' }" :locale="lunTransferLocale"
              id="lunTransferId" v-decorator="['lun', {
                rules: [
                  // {required:true, message: $t('Enter')+$t('User-group-name')},
                ],
                // initialValue: targetClient.username
              }]" />
          </a-spin>
        </a-form-item>
      </a-form>
      <div class="draw-bottom-btn">
        <a-button :style="{ marginRight: '8px' }" @click="handleCancel" style="width:80px">
          {{ $t('Cancel') }}
        </a-button>
        <a-button type="primary" @click="handleAddUserGroup" :loading="submitLoading" style="width:80px">
          {{ $t('Sure') }}
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
export default {
  name: "AddClientGroup",
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    targetsData: {
      type: Array,
      required: true,
      default: () => { return [] }
    },
    lunsData: {
      type: Array,
      required: true,
      default: () => { return [] }
    },
    isLoadingForm: {
      type: Boolean,
    }
  },

  data() {
    return {
      drawerVisible: false,
      form: this.$form.createForm(this),
      formDirection: 'vertical',
      formLayout: {
        // labelCol: {span:4},
        // wrapperCol: {span:18}
      },
      clientData: [],
      lunData: [],
      targetClientKeys: [],
      targetLunKeys: [],
      clientTransferLocale: {
        itemUnit: '',
        itemsUnit: '',
        notFoundContent: this.$t('List-empty'),
        searchPlaceholder: this.$t('Enter') + this.$t('Client')
      },
      lunTransferLocale: {
        itemUnit: '',
        itemsUnit: '',
        notFoundContent: this.$t('List-empty'),
        searchPlaceholder: this.$t('Enter') + this.$t('Lun-name')
      },
      submitLoading: false,
      drawerBodyStyle: {
        paddingBottom: '40px !important',
        // height: '80%',
        // overflow: 'auto'
      },
      chapChecked: false,
      twoWayChecked: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },
      inputId: 0,
      clientNameReg: /^iqn\.[0-9]{4}\-(0[1-9]|1[0-2])\.com(\.[\-0-9a-zA-Z]+)+(:[\-0-9a-zA-Z]+)$/
    }
  },

  watch: {
    visible(newValue) {
      this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
      this.drawerVisible = newValue;
    },
    lunsData() {
      this.handleLuns();
    },
  },

  methods: {
    // 验证客户端名字
    validatorClientName(rule, value, callback) {
      if (value && value.length > 64 && this.clientNameReg.test(value)) {
        callback(this.$t('Length-need-less-64'));
      } else {
        const keys = this.form.getFieldValue('keys');
        let repeatNum = 0;
        keys.forEach(item => {
          if (value === this.form.getFieldValue(`clients[${item}]`)) {
            repeatNum++
          }
        })
        if (repeatNum > 1) {
          callback(this.$t('Has-repeat-client'));
        } else {
          // keys.forEach(item => {
          //   if(value !== this.form.getFieldValue(`clients[${item}]`)) {
          //     this.form.setFields({
          //       [`clients[${item}]`]: {value: this.form.getFieldValue(`clients[${item}]`),errors:null}
          //     })
          //   }
          // })
          callback();
        }
      }
    },

    // 通过target获取对应的客户端
    async changeTarget(value) {
      const res = await this.$api.iscsi.getClientLunByTargetRequest({ target: value });
      // console.log('target对应的客户端', res)
      let finalData = [];
      res.data.clients.forEach(item => {
        finalData.push({
          key: item,
          title: item
        })
      })
      this.targetClientKeys = [];
      this.clientData = [...finalData];
    },

    // 处理传过来的lun
    handleLuns() {
      let finalData = [];
      this.lunsData.forEach(item => {
        finalData.push({
          key: item,
          title: item
        })
      })
      this.lunData = [...finalData];
    },

    //提交新增用户组
    handleAddUserGroup(e) {
      e.preventDefault();
      this.form.validateFields(async (err, val) => {
        if (!err) {
          this.submitLoading = true;
          const clients = val.keys.map(key => val.clients[key]);
          const params = {
            host_group: val.groupName,
            target: val.target,
            iqn: clients,
            lun: val.lun,
            username: this.chapChecked ? val.username : undefined,
            password: this.chapChecked ? val.pwd : undefined,
            mutual_username: this.twoWayChecked ? val.reverse_username : undefined,
            mutual_password: this.twoWayChecked ? val.reverse_pwd : undefined,
          };
          try {
            const res = await this.$api.iscsi.addUserGroupRequest(params);
            if (res && res.data) {
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              this.$emit('updateUserGroup');
            }
          } catch {
            this.handleCancel();
          }
          this.handleCancel();
        }
      })
    },

    //改变Lun穿梭框选项
    changeLunTransfer(targetKeys, direction, moveKeys) {
      // console.log(targetKeys, direction, moveKeys);
      this.targetLunKeys = targetKeys;
    },

    //改变客户端穿梭框选项
    changeClientTransfer(targetKeys, direction, moveKeys) {
      this.targetClientKeys = targetKeys;
    },

    //穿梭框搜索
    filterOption(inputValue, option) {
      return option.title.indexOf(inputValue) > -1;
    },

    //渲染穿梭框的数据格式
    renderRowData(item) {
      return item.title;
    },

    //取消抽屉显示
    handleCancel() {
      this.$emit('closeUserGroupDrawer', 'add');
      this.submitLoading = false;
      this.targetClientKeys = [];
      this.targetLunKeys = [];
      this.chapChecked = false;
      this.twoWayChecked = false;
      this.form.resetFields();
    },

    //改变chap认证的选择状态
    changeChapCheck(e) {
      this.chapChecked = e.target.checked;
      if (!e.target.checked) {
        this.twoWayChecked = false;
      }
    },

    //改变双向认证的选择状态
    changeTwoWayCheck(e) {
      this.twoWayChecked = e.target.checked;
    },

    remove(k) {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');
      // We need at least one passenger
      // if (keys.length === 1) {
      //   return;
      // }

      // can use data-binding to set
      form.setFieldsValue({
        keys: keys.filter(key => key !== k),
      });
    },

    add() {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');
      const nextKeys = keys.concat(this.inputId++);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    },
  },
}
</script>
<style scoped>
.draw-bottom-btn {
  /* float: right;
		padding-bottom: 20px; */
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 4px 4px;
}

::v-deep.ant-transfer-list-header {
  background: #e8e8e8;
}

/* 穿梭框标题位置互换 */

::v-deep#lunTransferId .ant-transfer-list-header-selected>span:nth-child(1),
::v-deep#clientTransferId .ant-transfer-list-header-selected>span:nth-child(1) {
  float: right;
}

::v-deep#lunTransferId .ant-transfer-list-header-selected>span:nth-child(2),
::v-deep#clientTransferId .ant-transfer-list-header-selected>span:nth-child(2) {
  /* float: left; */
  position: relative;
  left: 0;
}
</style>